<?php
namespace Home\Controller;
use Think\Controller;
/*
 * 微信入口文件
 */
class WechatController extends BaseController {
    public function index(){
	    $options = C('WECHAT_OPTIONS');
	    $wechatObj = new \Org\WechatTest\WechatTest($options);

	    //创建自定义菜单
//	    $wechatObj->createMenu();

	    //验证或回复消息
	    if($_GET["echostr"]){
		    $wechatObj->valid();
	    }else{
		    $wechatObj->responseMsg();
	    }
	}

	/*
	 * 微信授权
	 */
	public function wechatauth(){
		session_start();
		$options = C('WECHAT_OPTIONS');
		$appid = $options['appid'];
		$appsecret = $options['appsecret'];
		$siteurl = C('siteurl');

		//获取access_token
		$code = I('code');
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
		$info = json_decode(curl_get($url));
		$access_token = $info->access_token;
		$openid = $info->openid;
		$refresh_token  = $info->refresh_token;

		//检测openid是否有效
		$checkurl = "https://api.weixin.qq.com/sns/auth?access_token=$access_token&openid=$openid";
		$checkinfo = json_decode(curl_get($checkurl));

		if($checkinfo->errcode != 0){
			//刷新access_token
			$refreshurl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=$appid&grant_type=refresh_token&refresh_token=$refresh_token";
			$refreshinfo = json_decode(curl_get($refreshurl));
			$access_token = $refreshinfo->access_token;
			$openid = $refreshinfo->openid;
		}

		//拉取用户信息
		$getuerinfourl = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
		$userinfo = json_decode(curl_get($getuerinfourl));

		if($userinfo->openid){
			//添加或者更新user表
			$userinfo_tab = M('user');
			$userinfo_arr = array(
				'openid'     => $userinfo->openid,
				'nickname'   => $userinfo->nickname,
				'sex'        => $userinfo->sex,
				'province'   => $userinfo->province,
				'city'       => $userinfo->city,
				'country'    => $userinfo->country,
				'headimgurl' => $userinfo->headimgurl,
				'privilege'  => $userinfo->privilege,
				'unionid'    => $userinfo->unionid,
			);

			$wheredata['openid'] = $openid;

			$user_info = $userinfo_tab->where($wheredata)->find();
			if($user_info){
				$id = $user_info['id'];
				$updatewhere['id'] = $id;
				$userinfo_arr['updatetime'] = date('Y-m-d H:i:s',time());
				$userinfo_tab->where($updatewhere)->save($userinfo_arr);
			}else{
				$userinfo_arr['createtime'] = date('Y-m-d H:i:s',time());
				$id = $userinfo_tab->add($userinfo_arr);
			}
			$_SESSION['wxuserid'] = $id;

			//跳转到地址
			$state = I('state');
			$target = isset($state) ? $state : 'HOME';
			switch ($target) {
				case 'HOME':
					$redirecturl = $siteurl.'/index.php';
					break;
				default:
					$redirecturl = $siteurl . '/index.php/Home/Wechat';
					break;
			}

			header("Location: $redirecturl");
		}else{
			//拒绝授权
			$redirecturl = $siteurl.'/index.php/Home/Wechat';
			header("Location: $redirecturl");
		}

	}
}